package cn.base.web.config.feign;

import cn.rengy.auth.TokenType;
import cn.rengy.auth.entity.principal.Identity;
import cn.rengy.auth.jwt.JwtCreator;
import cn.rengy.util.servlet.ServletUtil;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import io.jsonwebtoken.ClaimsBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.impl.DefaultClaims;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.ServletRequestUtils;

import java.security.Principal;
import java.time.Duration;
import java.util.Date;
@Component
public class FeignAuthRequestInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate template) {
        //调用其他微服务
        ClaimsBuilder claimsBuilder= Jwts.claims()
                //.issuer("gateway")//签发主体
                .expiration(new Date(System.currentTimeMillis()+Duration.ofSeconds(10).toMillis()));//过期时间10秒
        //获取当前identity
        Principal principal=ServletUtil.getPrincipal();
        String access_token= JwtCreator.createToken(claimsBuilder.build(),(Identity)principal);
        //设置token
        template.header(HttpHeaders.AUTHORIZATION, TokenType.INNER.concat(access_token));
    }
}
